package info.androidhive.jsonparsing;

import info.androidhive.jsonparsing.R;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends ListActivity {

	private ProgressDialog pDialog;

	// URL to get contacts JSON
	//private static String url = "http://api.androidhive.info/contacts/"; 
	private static String url = "http://192.168.1.137/karaoke-All.php";
	//private static String url = "http://192.168.1.137/karaoke.php";
	// JSON Node names

	private static final String TAG_CONTACTS = "song";
	private static final String TAG_NUMBERSONG = "id";
	private static final String TAG_TITLE = "title";
	private static final String TAG_TITLESIMPLE = "title_simple";
	private static final String TAG_LANG = "lang";
	private static final String TAG_LYRIC = "lyric";
	private static final String TAG_SOURCE = "source";
	
	// contacts JSONArray
	JSONArray lienlac = null;
	DBAdapter myDb;
	// Hashmap for ListView
	ArrayList<HashMap<String, String>> contactList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		openDB();
		contactList = new ArrayList<HashMap<String, String>>();

		ListView lv = getListView();

		// Listview on item click listener
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String name = ((TextView) view.findViewById(R.id.name))
						.getText().toString();
				String cost = ((TextView) view.findViewById(R.id.email))
						.getText().toString();
				String description = ((TextView) view.findViewById(R.id.mobile))
						.getText().toString();

				// Starting single contact activity
				Intent in = new Intent(getApplicationContext(),
						SingleContactActivity.class);
				in.putExtra(TAG_NUMBERSONG, name);
				in.putExtra(TAG_TITLE, cost);
				in.putExtra(TAG_LYRIC, description);
				startActivity(in);

			}
		});

		// Calling async task to get json
		//new GetAllSong().execute();
		GetSong();
	}
	//--------------------
	private void displayRecordSet(Cursor cursor) {
		
		if (cursor.moveToFirst()) {
			do {
				// Process the data:
				String numberSong = cursor.getString(DBAdapter.COL_NUMBERSONG);
				String title = cursor.getString(DBAdapter.COL_TITLE);
				String lyric = cursor.getString(DBAdapter.COL_LYRIC);
				
				// tmp hashmap for single contact
				HashMap<String, String> contact = new HashMap<String, String>();

				// adding each child node to HashMap key => value
				contact.put(TAG_NUMBERSONG, numberSong);
				contact.put(TAG_TITLE, title);
				contact.put(TAG_LYRIC, lyric);
			

				// adding contact to contact list
				contactList.add(contact);
				
			
				
			} while(cursor.moveToNext());
		}
		
		// Close the cursor to avoid a resource leak.
		cursor.close();
		myDb.close();
		
		
		
	}
	//------------------------
private void GetSong ()  {
	
		pDialog = new ProgressDialog(MainActivity.this);
		pDialog.setMessage("Please wait...");
		pDialog.setCancelable(false);
		pDialog.show();
		
		Cursor cursor = myDb.getRowVN();
		//Cursor cursor = myDb.getRow();
		displayRecordSet(cursor);
		
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */
			ListAdapter adapter = new SimpleAdapter(
					MainActivity.this, contactList,
					R.layout.list_item, new String[] { TAG_NUMBERSONG, TAG_TITLE,
							TAG_LYRIC }, new int[] { R.id.name,
							R.id.email, R.id.mobile });

			setListAdapter(adapter);
	
	
}
	/**
	 * Async task class to get json by making HTTP call
	 * */
	private class GetAllSong extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

			Log.d("Response: ", "> " + jsonStr);
		
			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);
					
					// Getting JSON Array node
					lienlac = jsonObj.getJSONArray(TAG_CONTACTS);
					Log.d("Do dai chuoi: ", " " + lienlac.length());
					// looping through All Contacts
				
					for (int i = 0; i < lienlac.length(); i++) {
						JSONObject c = lienlac.getJSONObject(i);
						Log.d("Giá trị : ", " " + i);
						String numberSong = c.getString(TAG_NUMBERSONG);
						String title = c.getString(TAG_TITLE);
						String titleSimple=c.getString(TAG_TITLESIMPLE);
						String lang = c.getString(TAG_LANG);
						String lyric = c.getString(TAG_LYRIC);
						String source = c.getString(TAG_SOURCE);

					myDb.insertRow(Integer.parseInt( numberSong), title, titleSimple, lang, lyric, source);
					
						// tmp hashmap for single contact
						HashMap<String, String> contact = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						contact.put(TAG_NUMBERSONG, numberSong);
						contact.put(TAG_TITLE, title);
						contact.put(TAG_LYRIC, lyric);
					

						// adding contact to contact list
						contactList.add(contact);
					}
					myDb.close();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */
			ListAdapter adapter = new SimpleAdapter(
					MainActivity.this, contactList,
					R.layout.list_item, new String[] { TAG_NUMBERSONG, TAG_TITLE,
							TAG_LYRIC }, new int[] { R.id.name,
							R.id.email, R.id.mobile });

			setListAdapter(adapter);
		}

	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();	
		closeDB();
	}


	private void openDB() {
		myDb = new DBAdapter(this);
		myDb.open();
	}
	private void closeDB() {
		myDb.close();
	}

	
}